package com.data.boot.service.impl;

import cn.hutool.core.io.LineHandler;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.db.Db;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.data.boot.model.Field;
import com.data.boot.model.Record;
import com.data.boot.service.LoadDataService;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dwk on 2019/6/4.
 */
@Component
public class MySqlLoadDataService implements LoadDataService {
    private static final Log log = LogFactory.get();

    @Override
    public void load(String sql, String path, Record record) {
        try {
            FileReader reader = FileReader.create(new File(path));
            List<String[]> rowList = new ArrayList<>();

            reader.readLines(new LineHandler() {
                @Override
                public void handle(String line) {
                    String[] row = MySqlLoadDataService.this.parseLine(line, record);
                    rowList.add(row);
                    if (rowList.size() % 5000 == 0 && rowList.size() > 0) {//批量插入
                        String[][] rows = new String[5000][record.getLen()];
                        rowList.toArray(rows);
                        try {
                            Db.use().executeBatch(sql, rows);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        rowList.clear();
                    }
                }
            });
            if (rowList.size() > 0) {//插入剩余
                String[][] rows = new String[rowList.size()][record.getLen()];
                rowList.toArray(rows);
                Db.use().executeBatch(sql, rows);
            }
            log.info("mysql数据装载完毕");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public String[] parseLine(String line, Record record) {
        List<Field> fields = record.getFields();
        List<String> columns = new ArrayList<>();
        for (int i = 0; i < fields.size(); i++) {
            String column = line.substring(0, line.indexOf(fields.get(i).getTerminator()) +
                    fields.get(i).getTerminator().length()).replace(fields.get(i).getTerminator(), "");
            if (fields.get(i).getFlag()) {
                columns.add(column);
            }
            if (fields.get(i).getTerminator().equals("\n")) {
                line = line.substring(column.length() + fields.get(i).getTerminator().length(), line.length());
            }
        }
        String[] row = new String[columns.size()];
        columns.toArray(row);
        return row;
    }
}